package com.google.wave.robot.scrimborg;

import java.util.List;

import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.Event;
import com.google.wave.api.EventType;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;
import org.apache.log4j.Logger;

public class ScrimborgServlet extends AbstractRobotServlet {

	private static final long serialVersionUID = -1871274572181133776L;
	
	private static Logger log = Logger.getLogger(ScrimborgServlet.class.getSimpleName( ) );

	@Override
	public void processEvents(RobotMessageBundle message) {
		
		Wavelet wavelet = message.getWavelet();	

        if (message.wasSelfAdded()) {
        	
                Blip blip = wavelet.appendBlip();
                TextView textView = blip.getDocument();
                textView.append("Hi! I am Scrimborg! I shall try to protect you from email spam by offering short, safe and cute links " +
                		"to the email addresses you type into this wave. People willing to email you will go to this URL that will reveal " +
                		"your email address, after a simple test that automated scripts and bots cannot pass! Don't worry. I can't pass the tests either!" +
                		" You can find more information about my API at http://scr.im/");
        }
        
        log.debug( "event received [wave id = " + wavelet.getWaveId() + "] [wavelet id = " + wavelet.getWaveletId() + "] [wavelet title = "+ wavelet.getTitle() + "]");
        
        for( Event e : message.getEvents() ){
        	if( e.getType() == EventType.BLIP_SUBMITTED ){
        		
        		Blip blip = e.getBlip();
                TextView textView = blip.getDocument();
                String author = textView.getAuthor();
                String blipText = textView.getText();
				
                List<String> emails;
                
                if( ( emails = EmailDetector.parse( blipText ) ) != null ){
                	
                	for( String email : emails ){
                		
                		blipText = blipText.replaceAll( email, ScrimFetcher.fetchScrim( email ) );
                		
                	}

                	textView.replace( blipText );
                	textView.setAuthor( author );
                }
        	}
        }
	}
}